const app = getApp();
import {
    formatDate,
    formatterEnum
} from "../../utils/index"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: wx.getStorageSync('userInfo'),
        navBarHeight: app.globalData.navBarHeight,
        userInfo: null,
        isLoading: true,
        pageNum: 1,
        pageSize: 10,
        hasMore: true,
        orderStatusList: [{
            value: "1",
            name: "待付款",
        },
        {
            value: "2",
            name: "待发货",
        },
        {
            value: "3",
            name: "待收货",
        },
        {
            value: "4",
            name: "已完成",
        },
        {
            value: "5",
            name: "售后",
        }
        ],
        dataList: [],
        form: {
            goodsName: '',      // 商品名称
            goodsSize: '',   // 规格
            buyNum: '',         // 数量
            platformPrice: '',        // 单价
            orderTotalPrice: '0.00',  // 总金额（自动计算）
            payAmount: '',        // 消费积分
            goodsImg: [],
            feedbackContent: '',       // 反馈内容
            feedbackImages: []         // 反馈图片列表
        },
        statusList: [
            { label: "全部", value: 0 },
            { label: "待付款", value: 1 },
            { label: "待发货", value: 2 },
            { label: "待收货", value: 3 },
            { label: "已完成", value: 4 },
            { label: "售后", value: 5 }
        ],
        coupons: [
            { id: 1, label: '折扣券领取', type: '1', usageCount: 1 },
            { id: 2, label: '满减券领取', type: '2', usageCount: 1 },
            { id: 3, label: '积分暴涨券领取', type: '3', usageCount: 1 },
            { id: 4, label: '赠品券领取', type: '4', usageCount: 1 },
            { id: 5, label: '组合券领取', type: '5', usageCount: 1 },
            { id: 6, label: '抽奖券领取', type: '6', usageCount: 1 },
            { id: 7, label: '代理商专属折扣券领取', type: '7', usageCount: 1 },
            { id: 8, label: '采购返利券领取', type: '8', usageCount: 1 }
        ],
        cupponData: {

        },

        currentStatus: 0, // 默认为“全部”
        refundStatus: 0,
        orderStatus: 0,
        orderStatusName: "",
        fileList1: [],
        cloudPath1: [],
        goodsImg: [],
        _id: "",
        fileList: [],
        cloudPath: [],
        content: "", // 反馈内容
        imgs: [],
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const userInfo = wx.getStorageSync("userInfo") || null;
        if (!userInfo || !userInfo._openid) {
            wx.navigateTo({
                url: "/pages/login/index",
            });
        } else {
            this.setData({
                userInfo,
            });
        }
    },
    // 获取订单列表
    async fetchOrderList() {
        const res = await wx.cloud.callFunction({
            name: "getOrder",
            data: {
                type: "getOrderList",
                data: {
                    pageNum: this.data.pageNum,
                    pageSize: this.data.pageSize,
                    conditions: {
                        _openid: this.data.userInfo._openid,
                        orderStatus: this.data.active ? this.data.active : ""
                    }
                }
            }
        })
        if (res.result.code == 200) {
            const newData = res.result.data.map(item => {
                let createTime = new Date(item.createTime).getTime()
                return {
                    ...item,
                    orderStatusName: formatterEnum(this.data.orderStatusList, item.orderStatus),
                    createTime: formatDate(createTime, "YYYY-MM-DD HH:mm:ss"),
                    platformPrice: parseFloat(item.platformPrice).toFixed(2),
                    payAmount: parseFloat(item.payAmount).toFixed(2),
                    orderTotalPrice: parseFloat(item.orderTotalPrice).toFixed(2),
                }
            })
            const total = res.result.total
            const hasMore = (this.data.pageNum * this.data.pageSize) < total
            this.setData({
                dataList: this.data.pageNum == 1 ? newData : [...this.data.dataList, ...newData],
                hasMore,
                isLoading: false,
                orderStatusName: newData[0].orderStatusName,
                orderStatus: newData[0].orderStatus,
                currentStatus: newData[0].orderStatus,
                refundStatus: newData[0].refundStatus || 0,
                _id: newData[0]._id
            })
        }
    },

    getCurrentStatus() {
        this.fetchOrderList()
    },
    fetchAndUse(couponType, coupon) {
        wx.cloud.callFunction({
            name: 'getCoupon',
            data: {
                type: 'getCouponList',
                data: {
                    pageNum: 1,
                    pageSize: 20,
                    conditions: {
                        couponType,
                        _openid: this.data.userInfo._openid
                    }
                }
            }
        }).then(res => {
            // console.log("res-----", res)
            if (res.result.code == 200) {
                if (res.result.data.length > 0) {
                    // this.setData({
                    //     this.data.cupponData[type]: res.result.total
                    // })
                    this.setData({
                        [`cupponData[${couponType}]`]: res.result.data[0]
                    });
                    const currentData = res.result.data[0]
                    const now = Date.now()
                    const effectiveEndTime = currentData.effectiveEndTime;
                    if (now > effectiveEndTime) {
                        wx.showToast({ title: '当前优惠券已过期，不可使用', icon: 'none' });
                        return
                    } else {
                        // 进行使用
                        // 判断unclaimedCount
                        if (!currentData.receivedCount) {
                            wx.showToast({ title: '当前已领取的数量为0,不可使用', icon: 'none' });
                        }
                        if (currentData.unUsedCount >= coupon.usageCount) {
                            currentData.usedCount += coupon.usageCount;
                            currentData.unUsedCount = currentData.receivedCount - currentData.usedCount;
                            let data = {
                                ...currentData,
                            }
                            console.log('data', data)
                            this.updateCuppon(data)
                        } else {
                            wx.showToast({ title: '当前使用数量大于未使用数量', icon: 'none' });
                            return
                        }
                    }
                } else {
                    wx.showToast({ title: '当前无此类优惠券，不可使用', icon: 'none' });
                    return
                }
                // const newData = res.result.data.map(item => {

                //     return {
                //         ...item,
                //         effectiveStartTime: formatDate(item.effectiveStartTime),
                //         effectiveEndTime: formatDate(item.effectiveEndTime),
                //         couponType: formatterEnum(couponTypeList, item.couponType),
                //         couponSource: formatterEnum(this.data.couponSourceList, item.couponSource),
                //     }
                // })
                // const total = res.result.total
                // const hasMore = (this.data.pageNum * this.data.pageSize) < total
                // this.setData({
                //     dataList: this.data.pageNum == 1 ? newData : [...this.data.dataList, ...newData],
                //     hasMore,
                //     isLoading: false
                // })
            }
        }).catch(err => {
            console.log("err===", err)
        })
    },
    // 使用优惠券
    useCoupon(e) {
        const { index } = e.currentTarget.dataset;
        const coupon = this.data.coupons[index];
        coupon.usageCount = parseFloat(coupon.usageCount)
        if (!coupon.usageCount || coupon.usageCount <= 0) {
            wx.showToast({ title: '请输入正确的使用数量', icon: 'none' });
            return;
        }
        this.fetchAndUse(coupon.type, coupon)

        // 这里可以执行使用优惠券的逻辑，比如提交到服务器或更新状态
        // wx.showToast({
        //     title: `已使用 ${coupon.usageCount} 张${coupon.label}`,
        //     icon: 'success'
        // });

        console.log('使用优惠券:', coupon);
    },

    // 反馈内容输入事件
    onFeedbackInput(e) {
        this.setData({
            feedbackContent: e.detail.value
        });
    },

    // 处理反馈图片上传
    handleFeedbackUpload(e) {
        const { file } = e.detail;
        let feedbackImages = this.data.feedbackImages;
        feedbackImages.push(file);

        this.setData({
            feedbackImages
        });

        // 可选：上传到云存储（示例）
        wx.cloud.uploadFile({
            cloudPath: `feedback/${file.name}`,
            filePath: file.url
        }).then(res => {
            console.log('图片上传成功:', res.fileID);
        }).catch(err => {
            console.error('图片上传失败:', err);
        });
    },

    // 处理反馈图片删除
    handleFeedbackDelete(e) {
        const { index } = e.detail;
        let feedbackImages = this.data.feedbackImages;
        feedbackImages.splice(index, 1);

        this.setData({
            feedbackImages
        });
    },


    // 提交反馈
    submitFeedback() {
        const { feedbackContent, feedbackImages } = this.data;

        if (!feedbackContent.trim()) {
            wx.showToast({ title: '请输入反馈内容', icon: 'none' });
            return;
        }

        // 提交反馈逻辑（示例：打印反馈信息）
        console.log('提交反馈:', {
            content: feedbackContent,
            images: feedbackImages.map(img => img.url)
        });

        wx.showToast({ title: '提交成功', icon: 'success' });
    },

    //上面是模拟 下面是调取接口
    // 图片上传
    handleUpload(e) {
        wx.showLoading({
            title: '上传中···',
            mask: true,
        })
        wx.cloud.uploadFile({
            cloudPath: `feedback/feedback${new Date().getTime()}.png`,
            filePath: e.detail.file.url
        }).then(data => {
            wx.hideLoading()
            let fileList = this.data.fileList
            fileList.push(e.detail.file)
            let cloudPath = this.data.cloudPath
            cloudPath.push(data)
            let imgs = cloudPath.map(item => item.fileID)
            this.setData({
                fileList,
                cloudPath,
                imgs,
            })
            wx.showToast({
                title: '上传成功',
                icon: 'none'
            });
        }).catch(e => {
            wx.showToast({
                title: '上传失败',
                icon: 'none'
            });
            // console.log(e);
        });
    },
    // 图片上传-删除
    handleUploadDel(e) {
        let fileList = this.data.fileList
        fileList.splice(e.detail.index, 1)
        let cloudPath = this.data.cloudPath
        cloudPath.splice(e.detail.index, 1)
        let imgs = this.data.imgs
        imgs.splice(e.detail.index, 1)
        this.setData({
            fileList,
            cloudPath,
            imgs,
        })
    },
    // 提交
    handleSubmit() {
        if (this.data.content == "") {
            wx.showToast({
                title: '请输入反馈内容',
                icon: 'none'
            })
            return
        }

        let data = {
            _openid: this.data.userInfo._openid,
            content: this.data.content,
            imgs: this.data.imgs,
            createTime: new Date(),
        }

        if (data.imgs.length <= 0) {
            delete data.imgs
        }

        wx.cloud.callFunction({
            name: 'feedback',
            data: {
                type: "addFeedback",
                data,
            }
        }).then(res => {
            if (res.result.code == 200) {
                wx.showToast({
                    title: '提交成功',
                    icon: 'none'
                })
                setTimeout(() => {
                    wx.navigateBack()
                }, 2000);
            }
        }).catch(err => {
            // console.log("err=====", err)
        })
    },


    // 处理输入事件并校验正整数
    onUsageCountInput(e) {
        const value = e.detail;
        const { index } = e.currentTarget.dataset;
        // 确保输入值为正整数
        let newValue = parseInt(value);
        if (isNaN(newValue) || newValue <= 0) {
            newValue = ''; // 清空无效输入
        } else {
            newValue = newValue.toString();
        }

        const coupons = this.data.coupons;
        coupons[index].usageCount = newValue;

        this.setData({
            coupons
        });
    },

    // 切换状态
    changeStatus(e) {
        const value = e.currentTarget.dataset.value;
        this.setData({
            currentStatus: value
        });
    },

    // 付款操作
    handlePay(e) {
        const value = e.currentTarget.dataset.value;
        if (this.data.orderStatus !== parseInt(value)) {
            wx.showToast({ title: '当前订单状态不允许付款', icon: 'none' });
            return
        }
        wx.showToast({ title: '正在付款...' });
        this.switchStatus(this.data.orderStatus)
        // 调用支付接口
    },
    switchStatus(orderStatus) {
        let data = {}
        data._id = this.data._id
        data.orderStatus = orderStatus + 1
        wx.cloud.callFunction({
            name: 'getOrder',
            data: {
                type: "updateOrder",
                data
            }
        }).then(res => {
            if (res.result.code == 200) {
                wx.showToast({
                    title: '操作成功',
                    icon: 'none'
                })
            }
        }).catch(err => {
            // console.log("err=====", err)
        })
    },
    handleCouponClick(e) {
        const { type } = e.currentTarget.dataset;
        wx.showToast({ title: `点击了 ${type} 类型的券`, icon: 'none' });
        // 获取当前要优惠券列表 操作第一列的数据
        this.fetchAndGet(type)
        // 根据 type 执行具体逻辑，如跳转页面或弹窗提示等
    },
    // 获取优惠券列表数据
    fetchAndGet(couponType) {
        wx.cloud.callFunction({
            name: 'getCoupon',
            data: {
                type: 'getCouponList',
                data: {
                    pageNum: 1,
                    pageSize: 20,
                    conditions: {
                        couponType,
                        _openid: this.data.userInfo._openid
                    }
                }
            }
        }).then(res => {
            // console.log("res-----", res)
            if (res.result.code == 200) {
                if (res.result.data.length > 0) {
                    // this.setData({
                    //     this.data.cupponData[type]: res.result.total
                    // })
                    this.setData({
                        [`cupponData[${couponType}]`]: res.result.data[0]
                    });
                    const currentData = res.result.data[0]
                    const now = Date.now()
                    const effectiveEndTime = currentData.effectiveEndTime;
                    if (now > effectiveEndTime) {
                        wx.showToast({ title: '当前优惠券已过期，不可领取', icon: 'none' });
                        return
                    } else {
                        // 进行领取
                        // 判断unclaimedCount 
                        if (currentData.unclaimedCount > currentData.availableNum) {
                            currentData.receivedCount += currentData.availableNum;
                            currentData.unclaimedCount -= currentData.availableNum;
                            currentData.unUsedCount = currentData.receivedCount - currentData.usedCount;
                            let data = {
                                ...currentData,
                            }
                            console.log('data', data)
                            this.updateCuppon(data)
                        }
                    }
                } else {
                    wx.showToast({ title: '当前无此类优惠券，不可领取', icon: 'none' });
                    return
                }
                // const newData = res.result.data.map(item => {

                //     return {
                //         ...item,
                //         effectiveStartTime: formatDate(item.effectiveStartTime),
                //         effectiveEndTime: formatDate(item.effectiveEndTime),
                //         couponType: formatterEnum(couponTypeList, item.couponType),
                //         couponSource: formatterEnum(this.data.couponSourceList, item.couponSource),
                //     }
                // })
                // const total = res.result.total
                // const hasMore = (this.data.pageNum * this.data.pageSize) < total
                // this.setData({
                //     dataList: this.data.pageNum == 1 ? newData : [...this.data.dataList, ...newData],
                //     hasMore,
                //     isLoading: false
                // })
            }
        }).catch(err => {
            console.log("err===", err)
        })
    },
    updateCuppon(data) {
        wx.cloud.callFunction({
            name: 'getCoupon',
            data: {
                type: "updateCoupon",
                data
            }
        }).then(res => {
            if (res.result.code == 200) {
                wx.showToast({
                    title: '操作成功',
                    icon: 'none'
                })
                // setTimeout(() => {
                //     wx.navigateBack()
                // }, 2000);
            }
        }).catch(err => {
            // console.log("err=====", err)
        })
    },

    // 收货操作
    handleReceive(e) {
        const value = e.currentTarget.dataset.value;
        if (this.data.orderStatus !== parseInt(value)) {
            wx.showToast({ title: '当前订单状态不允许收货', icon: 'none' });
            return
        }
        wx.showModal({
            title: '提示',
            content: '确认收货？',
            success: (res) => {
                if (res.confirm) {
                    wx.showToast({ title: '已收货' });
                    // 更新订单状态逻辑
                    this.switchStatus(this.data.orderStatus)
                }
            }
        });
    },

    // 售后申请
    handleAfterSale(e) {
        const value = e.currentTarget.dataset.value;
        if (this.data.orderStatus !== parseInt(value)) {
            wx.showToast({ title: '当前订单状态不允许售后', icon: 'none' });
            return
        }
        wx.navigateTo({
            url: '/pages/after-sale/after-sale'
        });
    },

    // 退款操作
    handleRefund(e) {
        const value = e.currentTarget.dataset.value;
        if (this.data.orderStatus !== parseInt(value)) {
            wx.showToast({ title: '当前订单状态不允许申请退款', icon: 'none' });
            return
        }
        wx.showModal({
            title: '确认申请',
            content: '是否确认申请退款？',
            success: (res) => {
                if (res.confirm) {
                    wx.showToast({ title: '已申请退款' });
                    this.switchStatus(4)
                    // 调用退款接口
                }
            }
        });
    },
    // 商品图片-图片上传
    handleUpload1(e) {
        wx.showLoading({
            title: '上传中···',
            mask: true,
        })
        wx.cloud.uploadFile({
            cloudPath: `goods/goods${new Date().getTime()}.png`,
            filePath: e.detail.file.url
        }).then(data => {
            wx.hideLoading()
            let fileList1 = this.data.fileList1
            fileList1.push(e.detail.file)
            let cloudPath1 = this.data.cloudPath1
            cloudPath1.push(data)
            let goodsImg = cloudPath1.map(item => item.fileID)
            console.log('fileList1', fileList1, 'cloudPath1', cloudPath1, "goodsImg", goodsImg)
            this.setData({
                fileList1,
                cloudPath1,
                goodsImg,
            })
            wx.showToast({
                title: '上传成功',
                icon: 'none'
            });
        }).catch(e => {
            wx.showToast({
                title: '上传失败',
                icon: 'none'
            });
            // console.log(e);
        });
    },
    // 商品图片-图片上传-删除
    handleUploadDel1(e) {
        let fileList1 = this.data.fileList1
        if (fileList1.length <= 1) {
            wx.showToast({
                title: '请至少上传一张图片',
                icon: 'none'
            })
            return
        }
        fileList1.splice(e.detail.index, 1)
        let cloudPath1 = this.data.cloudPath1
        cloudPath1.splice(e.detail.index, 1)
        let goodsImg = this.data.goodsImg
        goodsImg.splice(e.detail.index, 1)
        this.setData({
            fileList1,
            cloudPath1,
            goodsImg,
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // this.getTabBar().init();
    },
    onUploadSuccess(event) {
        const { index, url } = event.detail;
        const newImageList = [...this.data.form.goodsImg];
        newImageList[index] = { url };  // 替换或添加新图片
        this.setData({
            'form.goodsImg': newImageList
        });
        console.log('上传成功:', url);
    }, onDeleteImage(event) {
        const { index } = event.detail;
        const newImageList = this.data.form.goodsImg.filter((_, i) => i !== index);
        this.setData({
            'form.goodsImg': newImageList
        });
    }, onUploadFail(event) {
        wx.showToast({ title: '上传失败', icon: 'none' });
        console.error('上传失败:', event.detail);
    },
    // 邀请角色
    roleUrl(e) {
        const {
            type
        } = e.currentTarget.dataset
        console.log('e', type)
        switch (type) {
            case "1":
                // 会员
                wx.navigateTo({
                    url: "/pages/invited/index?type=1",
                });
                break;
            case "2":
                // 代理商
                wx.navigateTo({
                    url: "/pages/invited/index?type=2",
                });
                break;
            default:
                return;
        }
    },

    showProductPicker(e) {
        const goodsName = e.detail;
        this.setData({
            'form.goodsName': goodsName
        });
    },
    showSpecPicker(e) {
        const goodsSize = e.detail;
        this.setData({
            'form.goodsSize': goodsSize
        });
    },
    onInputQuantity(e) {
        const buyNum = e.detail;
        this.updateForm({ buyNum });
    },

    onInputUnitPrice(e) {
        const platformPrice = e.detail;
        this.updateForm({ platformPrice });
    },

    onPointsUsedInput(e) {
        const payAmount = e.detail;
        this.setData({
            'form.payAmount': payAmount
        });
    },
    submitOrder() {
        console.log(this.data.form)
        // 这里可以调用云函数或接口提交订单

        const { goodsName, goodsSize, buyNum, platformPrice, orderTotalPrice, payAmount } = this.data.form;
        console.log('提交订单:', {
            goodsName, goodsSize, buyNum, platformPrice, orderTotalPrice, payAmount
        });
        if (!goodsName || !goodsSize || !buyNum || !platformPrice) {
            wx.showToast({ title: '请填写完整信息', icon: 'none' });
            return;
        }
        let goodsImg = this.data.goodsImg
        if (goodsImg.length == 0) {
            wx.showToast({ title: '请上传图片', icon: 'none' });

        }
        let data = {
            // "_id":
            //     "19e71531683163420095587f69369075",

            _openid:
                this.data.userInfo._openid,

            "activityPrice":
                150,

            "address":
                { "city": "深圳市", "detail": "深圳宝安大道123号", "district": "宝安区", "name": "会员1", "phone": "12345678901", "province": "广东省", "street": "深圳宝安大道" },

            "buyNum":
                2,

            "categoryId":
                "1",

            "categoryName":
                "名酒",

            "childCategoryId":
                "1",

            "childCategoryName":
                "酱香型",

            "couponDiscount":
                10,

            "couponId":
                "1",

            "couponName":
                "优惠券1",

            "couponNum":
                1,

            "couponType":
                "折扣券",



            "goodsDiscount":
                "90",

            "goodsDiscountNum":
                18,

            "goodsId":
                "2b83cb16681dbb3402b1505652aadb15",

            "goodsImg": [],

            "goodsName":
                "酒酒酒",

            "goodsSize":
                "500ml",

            "goodsUnit":
                "瓶",

            "isCoupon":
                "1",

            orderStatus:
                1,

            "orderTotalPrice":
                360,

            "payAmount":
                332,

            // "payTime":Fri May 30 2025 16: 14: 30 GMT +0800(中国标准时间),
            "platformPrice":
                180,

            "userInfo":
                { "level": 2, "phone": "12345678901", "userName": "会员1" },
        }



        // 新增
        data.createTime = new Date().getTime()

        data = { ...data, ...this.data.form, goodsImg }
        wx.cloud.callFunction({
            name: 'getOrder',
            data: {
                type: "addOrder",
                data,
            }
        }).then(res => {
            console.log("res-----", res)
            if (res.result.code == 200) {
                wx.showToast({
                    title: '新增成功',
                    icon: 'none'
                })
                // setTimeout(() => {
                //     wx.navigateBack()
                // }, 2000);
            }
        }).catch(err => {
            console.log("err=====", err)
        })


        // wx.showToast({ title: '提交成功', icon: 'success' });
    },


    updateForm(changes) {
        const { buyNum = this.data.form.buyNum, platformPrice = this.data.form.platformPrice } = changes;

        const orderTotalPrice = (parseFloat(buyNum || 0) * parseFloat(platformPrice || 0)).toFixed(2);
        this.setData({
            'form.buyNum': buyNum,
            'form.platformPrice': platformPrice,
            'form.orderTotalPrice': orderTotalPrice
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})